 /***********************************************************
 *  File_Name  : XJThreadSpecific.h
 *  File_Path   : 
 *  File_Encode : UTF8
 *  Description : 线程私有变量
 *  
 *  OS : Linux, UNIX
 *  LastVersion  : 20240215
 *      
 *  Author      : LiXiujie(李秀杰)
 *  Date        : 2024-2-15
 *  Version     : 20240215
 *  Description : 
 *                
 *  Edit Author : 
 *  Edit Date   : 
 *  Version     : 
 *  Description :
 *                
 ***********************************************************/
#ifndef XJTHREADSPECIFIC_H_
#define XJTHREADSPECIFIC_H_
#include <pthread.h>
#include <vector>
namespace XJUtilClass {


template <typename T>
class XJThreadSpecific {
public:
	XJThreadSpecific();
	virtual ~XJThreadSpecific();
public:
    /**
     * Initializes the thread-specific data key.
     */
	static void init() {
        if (pthread_key_create(&key_, &XJThreadSpecific::cleanup)) {

        }
    }
    /**
     * A static function to destroy the resource.
     */
    static void destroy() {
        pthread_key_delete(key_);
    }
    /**
     * Cleans up the memory allocated for the given pointer.
     *
     * @param ptr pointer to the memory to be cleaned up
     *
     * @return void
     */
    static void cleanup(void *ptr) {
        if (ptr == NULL) {
            return;
        }
        delete static_cast<T *>(ptr);
    }
    /**
     * A description of the entire C++ function.
     *
     * @param data description of parameter
     *
     * @return void
     *
     * @throws ErrorType description of error
     */
    static void set(T *data) {
        T *old = get();
        if (old != NULL) {
            cleanup(old);
        }
        pthread_setspecific(key_, data);
    }

    /**
     * Gets the value of type T from the current thread's specific data.
     *
     * @return pointer to the value of type T
     */
    static T*  get() {
        return static_cast<T *>(pthread_getspecific(key_));
    }
    // 线程特定数据键  
    static pthread_key_t key_;  
};
// 初始化静态成员  
template<typename T>  
    pthread_key_t XJThreadSpecific<T>::key_;
} /* namespace XJUtilClass */
#endif /* XJTHREADSPECIFIC_H_ */
